<template>
  <div>

    <!-- 权限点数据展示 -->
    <!-- show-checkbox显示选择框 -->
    <!-- default-expand-all 展开-->
    <!-- check-strictly切断父子之间的关系 -->
    <el-tree
      ref="tree"
      :data="permissionList"
      :props="{ label: 'name' }"
      node-key="id"
      show-checkbox
      default-expand-all
      check-strictly
    />

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// this.$refs.tree.getCheckedKeys()
import { getPermissionList } from '@/api/permission'// 获取权限列表详情
import { datatotree } from '@/utils'
import { assignPerm, getrolse } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: { // 角色的id
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: []

    }
  },
  created() {
    // 重新获取权限列表
    this.getPermissionList()
    // // 调用获取某一角色的权限
    this.getRoles()
  },

  methods: {
    // 点击取消
    cancelButton() {
      //   通知父级关闭弹窗
      this.$emit('close')
    },
    // 点击确定
    async setRolesBtn() {
      // 获取tree的选中的id,是个数组是权限的id
      const permIds = this.$refs.tree.getCheckedKeys()
      // 调接口发送api
      const res = await assignPerm({ id: this.roleId, permIds: permIds })
      // 给用户提示
      this.$message.success(res.message)
      // 通知父级关闭
      this.$emit('close')
      // 重新获取权限列表
      this.getPermissionList()
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = datatotree(res.data, '0')
    },
    // 获取某一角色的权限
    async getRoles() {
      const res = await getrolse(this.roleId)
      // 数据回填
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    }

  }

}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}

</style>
